package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * AxdrUnsigned64类
 * 实现64位无符号整数数据的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class AxdrUnsigned64 implements AxdrType {
    private java.math.BigInteger value = java.math.BigInteger.ZERO;
    private byte[] dataCode = null;

    public AxdrUnsigned64() {
    }

    public AxdrUnsigned64(java.math.BigInteger value) {
        this.value = value;
    }

    public java.math.BigInteger getValue() {
        return value;
    }

    public void setValue(java.math.BigInteger value) {
        this.value = value;
    }

    public byte[] getDataCode() {
        return dataCode;
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        // 解码8个字节的无符号整数（大端序）
        byte[] bytes = new byte[8];
        for (int i = 0; i < 8; i++) {
            bytes[i] = (byte) input.read();
        }
        this.value = new java.math.BigInteger(1, bytes);
        return 8;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        // 编码8个字节的无符号整数（大端序）
        byte[] bytes = this.value.toByteArray();
        // 确保是8个字节，如果不够则在前面补0
        byte[] result = new byte[8];
        int offset = 8 - bytes.length;
        for (int i = 0; i < bytes.length && i < 8; i++) {
            result[offset + i] = bytes[i];
        }

        try {
            for (int i = 0; i < 8; i++) {
                output.write(result[i]);
            }
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
        return 8;
    }

    /**
     * 编码并保存
     * 
     * @param encodingSizeGuess 编码大小预估
     */
    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    @Override
    public String toString() {
        return this.value.toString();
    }
}